/*
 * Copyright (C) 2021 HiHope Open Source Organization .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 *
 * limitations under the License.
 */
#include <string.h>
#include <unistd.h>
#include "cmsis_os2.h"

#include "iot_errno.h"
#include "iot_i2c.h"

#include "icm.h"

#include "ohos_types.h"


int icm_initialize(){
	unsigned char configure_reset = 0x01;
	unsigned char fifo_conf_data = 0x03;
	unsigned char buffer = 0x1F; //  temperature sensor enabled. RC oscillator is on, gyro and accelerometer low noise mode,
	unsigned char fifo_init = 0x40;

	uint32 status = 0;
	uint8 sendUserRSTCmd [] = {DEVICE_CONFIG, configure_reset};
	uint8 sendUserPowerCmd [] = {power_mgmt, buffer};
	uint8 sendUserFIFOInitCmd [] = {FIFO_CONFIG_INIT, fifo_init};
	uint8 sendUserFIFOCfgCmd [] = {FIFO_CONFIGURATION, fifo_conf_data};


	// HAL_I2C_Mem_Write(&hi2c1, device_address, DEVICE_CONFIG, 1, &configure_reset, 1, 100);
	status = IoTI2cWrite(WIFI_IOT_I2C_IDX_0, device_address, sendUserRSTCmd, sizeof(sendUserRSTCmd));
	osDelay(10);

	if (status != IOT_SUCCESS) {
            
		printf("===== Error: ICM40607 RST I2C write status = 0x%x! =====\r\n", status);

	}

	// HAL_I2C_Mem_Write(&hi2c1, device_address, power_mgmt, 1, &buffer, 1, 100);
	status = IoTI2cWrite(WIFI_IOT_I2C_IDX_0, device_address, sendUserPowerCmd, sizeof(sendUserPowerCmd));
	osDelay(10);

	if (status != IOT_SUCCESS) {
            
		printf("===== Error: ICM40607 PWR_MGMT0 I2C write status = 0x%x! =====\r\n", status);

	}

	// HAL_I2C_Mem_Write(&hi2c1, device_address, FIFO_CONFIG_INIT, 1, &fifo_init, 1, 100);
	status = IoTI2cWrite(WIFI_IOT_I2C_IDX_0, device_address, sendUserFIFOInitCmd, sizeof(sendUserFIFOInitCmd));
	osDelay(10);

	if (status != IOT_SUCCESS) {
            
		printf("===== Error: ICM40607 FIFOInit I2C write status = 0x%x! =====\r\n", status);

	}



	// HAL_I2C_Mem_Write(&hi2c1, device_address, FIFO_CONFIGURATION, 1, &fifo_conf_data, 1, 100);
	status = IoTI2cWrite(WIFI_IOT_I2C_IDX_0, device_address, sendUserFIFOCfgCmd, sizeof(sendUserFIFOCfgCmd));
	osDelay(10);

	if (status != IOT_SUCCESS) {
            
		printf("===== Error: ICM40607 FIFOCfg I2C write status = 0x%x! =====\r\n", status);

	}
	return status;
	
}

